package com.sq.universe.ureport.conf;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.bstek.ureport.provider.report.ReportFile;
import com.bstek.ureport.provider.report.ReportProvider;
import com.sq.universe.system.entity.FileEntity;
import com.sq.universe.system.entity.UserEntity;
import com.sq.universe.system.feign.FileFeign;
import com.sq.universe.ureport.dao.UreportDao;
import com.sq.universe.ureport.entity.UreportEntity;
import lombok.Setter;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.http.entity.ContentType;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@Setter
public class UreportProvider   implements ReportProvider {

    private static final String NAME = "mysql-provider";

    // 特定前缀，ureport底层会调用 getPrefix 方法来获取报表操作的Provier类
    private String prefix = "mysql:";

    // 是否禁用
    private boolean disabled;

    @Autowired
    private UreportDao ureportDao;

    @Autowired
    private FileFeign fileFeign;


    @Override
    public InputStream loadReport(String file) {
        UreportEntity ureportEntity = new UreportEntity();
        ureportEntity.setUreportName(getCorrectName(file));
        UreportEntity ureportFileEntity = ureportDao.get(ureportEntity);
        byte[] content = fileFeign.getByte(ureportFileEntity.getUreportFileId());
        ByteArrayInputStream inputStream = new ByteArrayInputStream(content);
        return inputStream;
    }

    @Override
    public void deleteReport(String file) {
        ureportDao.deleteByName(getCorrectName(file));
    }

    @Override
    public List<ReportFile> getReportFiles() {
        List<UreportEntity> list = ureportDao.query(new UreportEntity());
        List<ReportFile> reportList = new ArrayList<>();
        for (UreportEntity ureportFileEntity : list) {
            reportList.add(new ReportFile(ureportFileEntity.getUreportName(), ureportFileEntity.getUreportUpdateTime()));
        }
        return reportList	;
    }

    @Override
    public void saveReport(String file, String content) {
        try {
            file = getCorrectName(file);
            File tempFile = File.createTempFile(file.substring(0,file.lastIndexOf(".")),file.substring(file.lastIndexOf(".")));
            FileUtil.writeUtf8String(content,tempFile);
            UserEntity sysUser = new UserEntity();
            sysUser.setUserId(-1);

            FileInputStream fileInputStream = new FileInputStream(tempFile);
            MultipartFile multipartFile = new MockMultipartFile(tempFile.getName(), tempFile.getName(),
                    ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);

            FileEntity fileEntity = fileFeign.uploadBySystem(multipartFile,-1);
            UreportEntity ureportEntity = new UreportEntity();
            ureportEntity.setUreportName(getCorrectName(file));
            UreportEntity ureportFileEntity = ureportDao.get(ureportEntity);
            if(ureportFileEntity == null){
                ureportFileEntity = new UreportEntity();
                ureportFileEntity.setUreportName(file);
                ureportFileEntity.setUreportFileId(fileEntity.getFileId());
//            ureportFileEntity.set(content.getBytes());
                ureportFileEntity.setUreportCreateTime(new Date());
                ureportFileEntity.setUreportUpdateTime(new Date());
                ureportDao.insert(ureportFileEntity);


            }else{
//            ureportFileEntity.setContent(content.getBytes());
                ureportFileEntity.setUreportUpdateTime(new Date());
                ureportDao.update(ureportFileEntity);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public String getName() {
        return NAME;
    }

    @Override
    public boolean disabled() {
        return disabled;
    }

    @Override
    public String getPrefix() {
        return prefix;
    }

    /**
     * 获取没有前缀的文件名
     * @param name
     * @return
     */
    private String getCorrectName(String name){
        if(name.startsWith(prefix)){
            name = name.substring(prefix.length(), name.length());
        }
        return name;
    }

}
